// pages/index_detail/index_detail.js
var app = getApp(); //引用app.js
var commonURL = app.data.baseURL;
var commonURLYY = app.data.newURL;
var commonURLXX = app.data.lastURL;
var animation = wx.createAnimation({
  duration: 600, //动画持续时间，单位ms，默认值 400
  timingFunction: 'linear' //linear  动画一直较为均匀
});
Page({
  Img: '',
  openSettingBtnHidden: false,
  isShow: false,
  hasshareImg: false,
  isImg: false,
  getShow: false,
  isCanvas: false,
  qrcodeImg: '',
  issetting: false,
  data: {
    only_num: 1,
    msmpage: 1,
    "price": {
      dandu: "",
      tuangou: "",
      num: ""
    },
    "guige": {
      img: "",
      price: "0.00",
      list: [{
        id: "",
        name: ""
      }]
    },
    "guigeOptions": [],
    "currentItem": [],
    "disabledGuige": "none",
    "animation": "", //规格弹窗
    "imgUrls": [],
    "detail": {
      id: "",
      title: "",
      shichangprice: "",
      salenum: "",
      unit: "",
      img: "",
      kucun: "",
      selltype: "",
      deliverytype: ""
    },
    "navTab": ["图文详情", "商品属性"],
    "currentNavtab": "0",
    "likes": [],
    "close": "none", //关闭图标属性
    "xiangqing": {},
    "shuxing": []
  },
  onLoad: function (options) {
    var that = this;
    
    if (options.xiaoqu) { //判断是否听过分享链接进入的
      wx.setStorage({
        key: 'xiaoqu',
        data: JSON.parse(options.xiaoqu),
        success: function (res) {
          console.log('设置成功')
        },
        fail: function (res) {
          console.log('设置失败')
        }
      })
    }
    //判断是不是扫码进来
    if (decodeURIComponent(options.scene) !== 'undefined') {
      let scene = decodeURIComponent(options.scene);
      let indexid = scene.split("&")[0];
      let arearid = scene.split('&')[1];
      wx.request({
        url: commonURL + 'op=shop_area',
        data: {
          uniacid: app.data.GZHid,
          areaid: arearid,
          dev: 1
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res);
          var casArray = [];
          var item = {};
          var obj = {};
          console.log(res.data.length == 0)
          if (res.data.length == 0) {
            wx.showModal({
              title: '提示',
              content: '获取团长失败,请重新选择团长',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '../regimental/regimental',
                  })
                }
              }
            })
          } else {
            item['name'] = res.data[0].name,
              item['id'] = res.data[0].id,
              item['tzname'] = res.data[0].commander.name,
              item['join_hotline'] = res.data[0].join_hotline,
              item['merchant_entry'] = res.data[0].merchant_entry,
              item['avatar'] = res.data[0].commander.avatar,
              item['commanderTel'] = res.data[0].commander.mobile,
              item['address'] = res.data[0].address
            obj['name'] = res.data[0].name,
              obj['id'] = res.data[0].id,
              obj['item'] = item
            wx.setStorage({
              key: 'xiaoqu',
              data: obj,
            })
          }
        }
      })
      that.setData({
        indexid: indexid,
        arearid: areaid
      })
    } else {
      var indexid = options.id
      this.setData({
        indexid: indexid
      })
    }
    wx.request({
      url: commonURLXX + 'op=uniacid_shop',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        // wx.setNavigationBarTitle({ title: res.data.set.sname });//设置title文字
        that.setData({
          guess: res.data.bset.guess,
          sname: res.data.set.sname
        })
      }
    })
    var areaid = ''
    wx.getStorage({ //获取小区地址
      key: 'xiaoqu',
      success: function (res) {
        console.log(res.data.item, "xiaoqu")
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
        areaid = res.data.item.id
        that.setData({
          areaid: areaid
        })
      },
      fail: function () {
        wx.navigateTo({
          url: '../cell_selection/cell_selection',
        })
      }
    })
    wx.getStorage({
      key: 'shareqrImg',
      success: function (res) {
        that.setData({
          qrCode: res.data
        })
      },
    })
    var likes = [];
    that.get_goodsDetail(indexid, that);
    wx.request({ //ajax加载猜你喜欢
      url: commonURL + 'op=goods_rand',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        //console.log(res.data.list)
        if (res.data.list.length < 1) {
          return false
        }
        for (var i = 0; i < res.data.list.length; i++) {
          var obj = {};
          if (res.data.list[i].selltype == 0) {
            obj["id"] = res.data.list[i].id;
            obj["gimg"] = res.data.list[i].gimg;
            obj["title"] = res.data.list[i].gname;
            obj["price"] = res.data.list[i].oprice;
            obj["selltype"] = res.data.list[i].selltype;
          } else {
            obj["id"] = res.data.list[i].id;
            obj["gimg"] = res.data.list[i].gimg;
            obj["title"] = res.data.list[i].gname;
            obj["price"] = res.data.list[i].gprice;
            obj["selltype"] = res.data.list[i].selltype;
          }
          likes.push(obj);
        }
        that.setData({
          "likes": likes
        })
      }
    })
    console.log(indexid, wx.getStorageSync('xiaoqu').id)
    wx.request({
      url: app.data.baseURL + 'op=getWXACodeUnlimit',
      data: {
        appid: app.data.appid,
        secret: app.data.secret,
        uniacid: app.data.GZHid,
        opneid: app.data.openid,
        page: 'pages/index_only_detail/index_only_detail',
        dev: 1,
        scene: indexid + '&' + wx.getStorageSync('xiaoqu').id
      },
      success: function (res) {
        console.log(res)
        wx.downloadFile({
          url: res.data.data.surl,
          success: function (res) {
            that.setData({
              qrcodeImg11: res.tempFilePath,
              getShow: true
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },
  get_splist: function () {
    var that = this
    var num = that.data.msmpage;
    var gid = that.data.detail.id;
    console.log(gid)
    num++;
    console.log(num, gid, app.data.GZHid, )
    wx.request({ //商品购买列表
      url: commonURLYY + 'op=getbuylist',
      data: {
        page: num,
        uniacid: app.data.GZHid,
        goodsid: gid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        console.log(res.data.list.length)
        if (res.data.list.length > 0) {
          console.log(res.data.list, 888888)
          that.setData({
            msmpage: num
          })
          var data = res.data.list
          that.setData({
            pylist: that.data.pylist.concat(data)
          })
          var nickname = '';
          for (var i = 0; i < data.length; i++) {
            if (data[i].nickname.length > 10) {
              nickname = "pylist[" + i + "].nickname"
              that.setData({
                [nickname]: data[i].nickname.substring(0, 10) + '...'
              })
            }
          }
        } else {
          num--;
          wx.showToast({
            title: '已是全部记录',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },
  reduceCount: function (e) {
    var n = 0;
    console.log(e.currentTarget.dataset.only)
    n = e.currentTarget.dataset.only - 1
    if (n < 1) {
      n = 1;
      wx.showToast({
        title: '数量不能小于1！',
        icon: 'none',
        duration: 2000
      })
    }
    this.setData({
      only_num: n
    })
  },
  addCount: function (e) {
    var n = 0;
    console.log(e.currentTarget.dataset.only)
    n = e.currentTarget.dataset.only + 1
    this.setData({
      only_num: n
    })
  },
  share: function () {
    var that = this;
    if (!that.data.shareImage) {
      that.setData({
        isShow: true,
        issetting: false,
        isCanvas: true
      })
      wx.showLoading({
        title: '正在生成图片...',
        mask: true,
      });
      let yOffset = 0;
      const goodsTitle = that.data.detail.title;
      let goodsTitleArray = [];
      //为了防止标题过长，分割字符串,每行15个
      for (let i = 0; i < goodsTitle.length / 15; i++) {
        if (i > 2) {
          break;
        }
        goodsTitleArray.push(goodsTitle.substr(i * 15, 15));
      }
      const oprice = that.data.detail.oprice;
      const shichangprice = that.data.detail.shichangprice;
      const canvasCtx = wx.createCanvasContext('shareCanvas');
      //绘制背景
      canvasCtx.setFillStyle('white');
      canvasCtx.fillRect(0, 0, 390, 800);
      //绘制商品图片
      canvasCtx.drawImage(that.data.Img, 0, 0, 250, 150);
      //绘制商品标题
      yOffset = 100;
      canvasCtx.setFontSize(15);
      canvasCtx.setFillStyle('#333333');
      canvasCtx.setTextAlign('left');
      for (var i = 0; i < goodsTitleArray.length; i++) {
        canvasCtx.fillText(goodsTitleArray[i], 10, 180 + i * 20);
      }
      //折扣价
      if (oprice) {
        canvasCtx.setFontSize(18);
        canvasCtx.setFillStyle('#f9555c');
        canvasCtx.setTextAlign('left');
        canvasCtx.setFontSize(15);
        canvasCtx.setFillStyle('#f9555c');
        canvasCtx.setTextAlign('left');
        canvasCtx.fillText('¥' + oprice, 10, 210 + (goodsTitleArray.length - 1) * 20);
      }
      //绘制原价
      if (shichangprice) {
        const xOffset = (shichangprice.length / 2 + 1) * 24 + 50;
        canvasCtx.setFontSize(12);
        canvasCtx.setFillStyle('#999999');
        canvasCtx.setTextAlign('left');
        canvasCtx.fillText('原价:¥' + shichangprice, 10, 230 + (goodsTitleArray.length - 1) * 20);
        canvasCtx.setLineWidth(1);
        canvasCtx.moveTo(20, 226 + (goodsTitleArray.length - 1) * 20);
        canvasCtx.lineTo(20 + (shichangprice.toString().length / 2) * 20, 226 + (goodsTitleArray.length - 1) * 20);
        canvasCtx.setStrokeStyle('#ff0000');
        canvasCtx.stroke();
      }
      //绘制底部提示文字
      canvasCtx.setFillStyle('#f9555c');
      canvasCtx.setTextAlign('left');
      canvasCtx.setFontSize(12);
      canvasCtx.setFillStyle('#999999');
      canvasCtx.setTextAlign('left');
      canvasCtx.fillText('长按识别图中的小程序码', 10, 300);
      //绘制二维码
      // canvasCtx.drawImage(that.data.qrCode, 150, 220, 80, 80);
      canvasCtx.drawImage(that.data.qrcodeImg11, 150, 220, 80, 80);
      setTimeout(function () {
        canvasCtx.draw(false, function () {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 250,
            height: 320,
            destWidth: 1000,
            destHeight: 1280,
            canvasId: 'shareCanvas',
            success: function (res) {
              that.setData({
                shareImage: res.tempFilePath,
                issetting: true,
                ShowshareImg: res.tempFilePath
              })
              wx.hideLoading();
            },
            fail: function (res) {
              wx.hideLoading();
              wx.showToast({
                title: '错误，请稍后再试',
              })
            },
          })
        });
      }, 1200)
    } else {
      var that = this;
      that.setData({
        isShow: true,
        isCanvas: false,
        isImg: true,
        issetting: true
      })
    }
  },
  //获取是否授权相册权限
  handleSetting: function (e) {
    let that = this;
    // 对用户的设置进行判断，如果没有授权
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '若不打开授权，则无法将图片保存在相册中！',
        showCancel: false
      })
      that.setData({
        saveImgBtnHidden: true,
        openSettingBtnHidden: true
      })
    } else {
      that.setData({
        saveImgBtnHidden: false,
        openSettingBtnHidden: false,
        issetting: true
      })
      wx.showModal({
        title: '提示',
        content: '您已授权，赶紧将图片保存在相册中吧！',
        showCancel: false
      })
    }
  },
  //保存图片到相册
  SaveShareImg: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.shareImage,
      success: function (res) {
        wx.showModal({
          title: '存图成功',
          content: '图片成功保存到相册了，去发朋友圈咯~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                isShow: false
              })
            }
          }
        })
      },
      fail: function (res) {
        if (res.errMsg != 'saveImageToPhotosAlbum:fail cancel') {
          wx.showModal({
            title: '授权提示',
            content: '请去授权，否则无法分享到朋友圈哦！',
            success: function (res) {
              if (res.cancel) {
                that.setData({
                  openSettingBtnHidden: false,
                  issetting: true
                })
              } else {
                //点击确定
                that.setData({
                  openSettingBtnHidden: true,
                  issetting: false
                })
              }
            },
            fail: function (res) {
              wx.showToast({
                title: '错误，请稍后再试',
              })
            }
          })
        }
      }
    })
  },
  //取消保存
  CancelShareImg: function () {
    this.setData({
      isShow: false
    })
  },
  switchTab: function (e) {
    this.setData({
      currentNavtab: e.currentTarget.dataset.idx
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    var that = this;
    var xqname = '';
    var sname = '';
    var title = '';
    wx.getStorage({
      key: 'xiaoqu',
      success: function (res) {
        xqname = res.data.item.name
        wx.request({
          url: commonURLXX + 'op=uniacid_shop',
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            sname = res.data.set.sname
            title = xqname + '-' + sname
            wx.setNavigationBarTitle({
              title: title
            }); //设置title文字
          }
        })
        console.log(res.data.item, "xiaoqu")
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
      }
    })
    this.setData({
      disabledGuige: 'none'
    })
  },
  onHide: function () {
    // 页面隐藏
  },
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '-';
    var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
    return Y + M + D + h + m + s;
  },
  onUnload: function () {
    // 页面关闭
  },
  get_goodsDetail: function (indexid, that) {
    // //下载二维码
    console.log(this.data.optionId)
    // var data = res.data[indexid];
    var shuxing = [];
    var xiangqing;
    var imgUrls = [];
    var areaid = ''
    var that = this
    wx.getStorage({ //获取小区地址
      key: 'xiaoqu',
      success: function (res) {
        console.log(res.data.item, "xiaoqu")
        that.setData({
          region: res.data.item,
          xiaoqudw: res.data.item.name,
          phone: res.data.item.join_hotline,
          phone1: res.data.item.merchant_entry,
        });
        console.log(res.data.id, '获取小区');
        areaid = res.data.item.id
        that.setData({
          areaid: areaid
        })
        console.log(indexid, areaid)
        wx.request({ //ajax加载商品详情
          url: commonURL + 'op=goods_detail',
          data: {
            id: indexid,
            areaid: areaid
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data, 123555)
            that.setTimesklp(res.data.spike_start)
            console.log(res.data.spike_end)
            that.setData({
              spike: res.data.spike,
              cnum: res.data.cnum
              // carts: res.data.carts
            })
            console.log(res.data.id, app.data.GZHid, areaid)
            var gId = res.data.id
            wx.request({ //商品购买列表
              url: commonURLYY + 'op=getbuylist',
              data: {
                page: 1,
                uniacid: app.data.GZHid,
                goodsid: gId
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) { //朋友买了什么
                console.log(res)
                var data = res.data.list
                that.setData({
                  pylist: data
                })
                var nickname = '';
                for (var i = 0; i < data.length; i++) {
                  if (data[i].nickname.length > 10) {
                    nickname = "pylist[" + i + "].nickname"
                    that.setData({
                      [nickname]: data[i].nickname.substring(0, 10) + '...'
                    })
                  }
                }
              }
            })

            var data = res.data;
            if (data.advs.length == 0) { //获取轮播图片
              imgUrls.push(data.gimg);
            } else {
              for (var j = 0; j < data.advs.length; j++) {
                imgUrls.push(data.advs[j].thumb);
              }
            }
            if (data.params.length == 0) {
              shuxing = [{
                text1: "暂无属性信息"
              }];
            } else {
              for (var i = 0; i < data.params.length; i++) { //获取属性信息
                var obj = {};
                obj["text1"] = data.params[i].title;
                obj["text2"] = data.params[i].value;
                shuxing.push(obj);
              }
            }
            if (data.gdesc == "") {
              (xiangqing = "暂无详情信息")
            } else {
              xiangqing = data.gdesc;
              // console.log(xiangqing);
              // var arrimg=xiangqing.match(/(http:\/\/)[a-zA-Z0-9.\/]*(.jpg){0,1}/g);
              // var txt=xiangqing.match(/((&gt;)|(&lt;))[\u4e00-\u9fa5,，。？！“”""/;；、_-]{2,}((&gt;)|(&lt;))/g);
              //var txt=xiangqing.match(/((((&gt;)|(&lt;))[\u4e00-\u9fa5,，。？！“”""/;；、_-]{2,}((&gt;)|(&lt;))))|((&quot;))[\u4e00-\u9fa5,，。？！“”""/;；、_-]{2,}((&quot;))/g);
              // var arrtxt=[];
              // if(!!txt){
              //   for(var i=0;i<txt.length;i++){
              //     arrtxt[i]=txt[i].slice(4,-4);
              //   }
              // }
              that.setData({
                xiangqing: that.escapeHtml(xiangqing)
              })
            }
            that.setData({
              "imgUrls": imgUrls,
              "detail": {
                id: data.id,
                title: data.gname,
                shichangprice: data.mprice,
                spike_over:data.spike_end,
                spike_on:data.spike_start,
                spike_end:that.timestampToTime(Number(data.spike_end)),
                spike_start:that.timestampToTime(Number(data.spike_start)),
                oprice: data.oprice,
                salenum: data.salenum,
                unit: data.unit,
                img: data.gimg,
                yunfei: "",
                kuncun: data.gnum,
                selltype: data.selltype,
                deliverytype: data.deliverytype,
                hasoption: data.hasoption,
                weight: data.weight,
                isshow: data.isshow,
                gnum: data.gnum
              },
              "price": {
                dandu: data.oprice,
                tuangou: data.gprice,
                num: data.groupnum
              },
              //"xiangqing":xiangqing,
              "shuxing": shuxing,
              "wholesale_level": data.wholesale_level,
              "wholesale_num": data.wholesale_num,
              "is_wholesale": data.is_wholesale
            });
            wx.downloadFile({
              url: that.data.detail.img,
              success: function (res) {
                that.setData({
                  Img: res.tempFilePath,
                })
                // if (that.data.shareqrImg){
                //   hasshareImg:true
                // }
              },
              fail: function () {
                console.log('fail')
              }
            })

          }
        })
      },
      fail: function () {
        wx.navigateTo({
          url: '../cell_selection/cell_selection',
        })
      }
    })
  },
  formatDateTime: function (timeStamp) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  setTimesklp: function (time) {
    var that = this
    var num_timearr = [];
    setInterval(function () {
      var obj = {};
      time = Number(time)
      var totalSecond = time - Date.parse(new Date()) / 1000; //这边传一个时间戳
      if (totalSecond >= 0) {
        // 秒数
        var second = totalSecond;

        // 天数位
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;

        // 小时位
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;

        // 分钟位
        var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;

        // 秒位
        var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;
        var num_time = {};
        num_time = {
          dayStr: dayStr,
          hrStr: hrStr,
          minStr: minStr,
          secStr: secStr
        }
        that.setData({
          num_time: num_time
        })
      } else {
        num_time = {
          dayStr: '00',
          hrStr: '00',
          minStr: '00',
          secStr: '00'
        }
        that.setData({
          num_time: num_time
        })
      }
    }, 1000)
  },
  close: function (e) {
    this.setData({
      close: "none"
    })
  },
  open: function (e) {
    this.setData({
      close: "block"
    })
  },
  chooseGG: function (e) { //选择规格
    var that = this;
    var title = e.currentTarget.dataset.title;
    var options = that.data.guigeOptions;
    var currentItem = that.data.currentItem;
    var key = e.currentTarget.dataset.key;
    var guige = that.data.guige;
    currentItem[key].title = title;
    currentItem[key].item = e.currentTarget.dataset.index;
    that.setData({
      selectIndex: e.currentTarget.dataset.index
    })
    if (e.currentTarget.dataset.img) {
      guige.img = e.currentTarget.dataset.img
    } //如果规格图片存在，就替换图片
    for (var i = 0; i < options.length; i++) {

      for (var j = 0, ii = 0; j < currentItem.length; j++) {
        if (currentItem[j].title == "") {
          that.setData({
            "currentItem": currentItem,
            "guige": guige
          })
          return false;
        }
        var patt1 = new RegExp(currentItem[j].title);
        var result = patt1.test(options[i].title);
        result && ii++;
      }
      if (currentItem.length == ii) {
        var price = "";
        price = options[i].productprice
        guige.price = price;
      }
    }
    that.setData({
      "currentItem": currentItem,
      "guige": guige
    })
  },
  onShareAppMessage: function () { //分享页面
    var xiaoqu = JSON.stringify(wx.getStorageSync('xiaoqu'));
    return {
      title: this.data.detail.title,
      path: '/pages/index_only_detail/index_only_detail?id=' + this.data.detail.id + '&xiaoqu=' + xiaoqu,
      success: function (res) {
        console.log(res);
        console.log("转发成功:" + JSON.stringify(res));
      }
    }
  },
  gotoIndexDetail: function (e) {
    var _selltype = e.currentTarget.dataset.selltype;
    if (_selltype == '0') {
      wx.redirectTo({
        url: '../index_only_detail/index_only_detail?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.redirectTo({
        url: '../index_detail/index_detail?id=' + e.currentTarget.dataset.id,
      })
    }
  },
  gotoBuyPage: function (a) { //规格弹窗，确定按钮
    var that = this;
    for (var i = 0; i < that.data.currentItem.length; i++) {
      if (that.data.currentItem[i].item == "-1") { //判断是否选中规格
        wx.showToast({
          title: '请选择规格',
          icon: 'loading',
          duration: 1500
        })
        return false;
      }
    }
    wx.removeStorage({
      key: 'address'
    });
    for (var i = 0; i < that.data.guigeOptions.length; i++) {
      if (that.data.guigeOptions[that.data.selectIndex].cnum <= 0) {
        wx.showToast({
          title: '库存已被别人抢光,请稍后刷新页面再试',
          icon: 'none'
        })
        return;
      }
    }
    for (var jj = 0, title = ""; jj < that.data.currentItem.length; jj++) {
      title += ("+" + that.data.currentItem[jj].title);
    }
    var dataDetail = {
      id: that.data.detail.id,
      title: that.data.detail.title,
      price: that.data.price.tuangou,
      img: that.data.detail.img,
      selltype: that.data.detail.selltype,
      deliverytype: that.data.detail.deliverytype,
      weight: that.data.detail.weight,
      optionname: title.slice(1)
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    wx.request({
      url: commonURLYY + 'op=cart_add',
      data: {
        openid: app.data.openid,
        gid: this.data.indexid,
        areaid: this.data.region.id,
        guige: dataDetail.optionname
        // weight
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var detail_btn = wx.getStorageSync('detail_btn');
        if (res.data.status != 1) {
          wx.showToast({
            title: res.data.result,
            icon: 'loading',
            duration: 1000
          })
          return false;
        }
        if (detail_btn == 'shopcart') {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1000
          })

          that.setData({
            disabledGuige: 'none'
          })
        } else {
          wx.switchTab({
            url: '../shopcart/shopcart'
          })
        }
      }
    })
    // wx.navigateTo({
    //   url: (that.data.istuan)?'../index_buy/index_buy?istuan=true':'../index_buy/index_buy',
    // })
  },
  goto_shopcart: function (e) {
    var that = this;
    if (that.data.spike == 1) {
      if (that.data.detail.spike_on > Date.parse(new Date()) / 1000) {
        wx.showToast({
          title: '还未到抢购时间',
          icon: false
        })
        that.setData({
          hasblock: false
        })
        return
      }
      if (that.data.detail.spike_over < Date.parse(new Date()) / 1000) {
        wx.showToast({
          title: '已过了抢购时间',
          icon: false
        })
        that.setData({
          hasblock: false
        })
        return
      }
    }
    if (that.data.cnum <= 0) {
      wx.showToast({
        title: '库存已被抢完了',
      })
      return;
    }
    var {
      isshow,
      gnum
    } = this.data.detail;
    if (isshow == '3' || gnum == '0') return;
    wx.setStorageSync('detail_btn', 'shopcart');
    if (that.data.detail.hasoption == "1") { //有规格产品
      //弹出规格选择框
      that.ajaxGuige(that); //加载规格数据
      that.openGuige(that, true);
    } else { //无规格产品
      if (that.data.detail.kucun < 1) {
        wx.showToast({
          title: '库存不足,无法购买',
          icon: 'loading',
          duration: 2000
        })
      } else {
        this.add_shopcart(this.data.indexid);
      }
    }
  },
  gotoBuy_dan: function (e) {
    var that = this;
    if (that.data.spike == 1) {
      if (that.data.detail.spike_on > Date.parse(new Date()) / 1000) {
        wx.showToast({
          title: '还未到抢购时间',
          icon: false
        })
        that.setData({
          hasblock: false
        })
        return
      }
      if (that.data.detail.spike_over < Date.parse(new Date()) / 1000) {
        wx.showToast({
          title: '已过了抢购时间',
          icon: false
        })
        that.setData({
          hasblock: false
        })
        return
      }
    }
    if (that.data.cnum <= 0) {
      wx.showToast({
        title: '库存已被抢完了',
        icon: 'none'
      })
      wx.switchTab({
        url: '../shopcart/shopcart',
      })
      return;
    }
    if (that.data.is_wholesale == 1) {
      if (that.data.only_num >= that.data.wholesale_num) {
        var {
          isshow,
          gnum
        } = this.data.detail;
        if (isshow == '3' || gnum == '0') return;
        wx.setStorageSync('detail_btn', 'go_buy')
        if (that.data.detail.hasoption == "1") {
          console.log(1) //有规格产品
          //弹出规格选择框
          that.ajaxGuige(that);
          that.openGuige(that, false);
        } else { //无规格产品
          console.log(2)
          if (this.data.detail.kucun < 1) {
            wx.showToast({
              title: '库存不足,无法购买',
              icon: 'none',
              duration: 2000
            })

          } else {
            that.tiaozhuanDan(); //调用跳转函数
          }
        }
      } else {
        wx.showToast({
          title: '未达到起批数量！',
          icon: 'loading',
          duration: 2000
        })
      }
    } else {
      console.log(9)
      var {
        isshow,
        gnum
      } = this.data.detail;
      if (isshow == '3' || gnum == '0') return;
      wx.setStorageSync('detail_btn', 'go_buy')
      if (that.data.detail.hasoption == "1") { //有规格产品
        //弹出规格选择框
        that.ajaxGuige(that);
        that.openGuige(that, false);
      } else { //无规格产品
        if (this.data.detail.kucun < 1) {
          wx.showToast({
            title: '库存不足,无法购买',
            icon: 'loading',
            duration: 2000
          })

        } else {
          that.tiaozhuanDan(); //调用跳转函数
        }
      }
    }
  },
  closeGuige: function () {
    var that = this;
    animation.height("0").step();
    that.setData({
      animation: animation.export() //关闭规格选择
    })
    setTimeout(function () {
      that.setData({
        disabledGuige: "none"
      });
    }, 600)
  },
  openGuige: function (that, istuan) { //选择规格动画
    that.setData({
      disabledGuige: "block"
    });
    animation.height("540rpx").step();
    that.setData({
      animation: animation.export(), //输出动画
      istuan: istuan
    })
  },
  tiaozhuanDan: function () { //单买跳转函数
    wx.removeStorage({
      key: 'address'
    }); //清除缓存，修复地址不对应bug
    var dataDetail = {
      id: this.data.detail.id,
      title: this.data.detail.title,
      price: this.data.price.dandu,
      img: this.data.detail.img,
      selltype: this.data.detail.selltype,
      deliverytype: this.data.detail.deliverytype,
      weight: this.data.detail.weight
    }
    wx.setStorage({
      key: "indexBuyDetail",
      data: dataDetail
    })
    wx.request({
      url: commonURLYY + 'op=cart_add',
      data: {
        openid: app.data.openid,
        gid: this.data.indexid,
        areaid: this.data.region.id,
        guige: '',
        num: this.data.only_num
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        var detail_btn = wx.getStorageSync('detail_btn');
        if (res.data.status == 0) {
          wx.showToast({
            title: res.data.result,
            icon: 'none',
            duration: 1000
          })
          wx.switchTab({
            url: '../shopcart/shopcart',
          })
          return false;
        } else if (res.data.status == 1) {
          wx.showToast({
            title: res.data.result,
            icon: 'none',
          })
        }
        wx.switchTab({
          url: '../shopcart/shopcart',
        })
      }
    })
  },
  // tiaozhuanTuan:function(){//团购跳转函数
  //   wx.removeStorage({key: 'address'});
  //   var dataDetail={
  //     id:this.data.detail.id,
  //     title:this.data.detail.title,
  //     price:this.data.price.tuangou,
  //     img:this.data.detail.img,
  //     selltype:this.data.detail.selltype,
  //     deliverytype:this.data.detail.deliverytype,
  //     weight:this.data.detail.weight
  //   }
  //   wx.setStorage({
  //     key:"indexBuyDetail",
  //     data:dataDetail
  //   })
  //   wx.navigateTo({
  //     url: '../index_buy/index_buy?istuan=true',
  //   })
  // },
  ajaxGuige: function (that) {
    var ajaxguige = wx.getStorageSync('guige');
    if (ajaxguige.id == that.data.detail.id) { //先判断该商品规格是否存在缓存中，否则ajax加载数据
      var data = ajaxguige.allspecs;
      var currentItem = [];
      for (var i = 0; i < data.length; i++) {
        currentItem.push({
          title: "",
          item: "-1"
        });
      }
      if (data.length < 1) {
        return false
      }
      that.setData({
        guige: {
          img: that.data.detail.img,
          price: "0.00",
          list: data
        },
        guigeOptions: ajaxguige.options,
        currentItem: currentItem
      })
    } else {
      wx.request({
        url: commonURL + 'op=goods_guige',
        data: {
          id: that.data.detail.id,
          areaid: that.data.areaid
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          var data = res.data.allspecs;
          var currentItem = [];
          for (var i = 0; i < data.length; i++) {
            currentItem.push({
              title: "",
              item: "-1"
            });
          }
          if (data.length < 1) {
            return false
          }
          that.setData({
            guige: {
              img: that.data.detail.img,
              price: "0.00",
              list: data
            },
            guigeOptions: res.data.options,
            currentItem: currentItem
          })
          // var dataguige = res.data;
          // dataguige.id = that.data.detail.id;
          // wx.setStorage({//把规格存储在缓存中
          //     key: 'guige',
          //     data: dataguige,
          // })
        }
      })
    }
  },
  add_shopcart: function (gid) {
    wx.request({
      url: commonURLYY + 'op=cart_add',
      data: {
        openid: app.data.openid,
        gid: gid,
        areaid: this.data.region.id,
        num: this.data.only_num
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        if (res.data.status == 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1000
          })
        } else if (res.data.status == 0) {
          wx.showToast({
            title: res.data.result,
            icon: 'none',
          })
          return
        } else if (res.data.cnum <= 0) {
          wx.showToast({
            title: '该商品库存已被抢占，请稍后再试',
            icon: 'none',
          })
          return
        }
      }
    })
  },
  escapeHtml: function (text) {
    var a = text.replace(/(\&lt;)/g, "<");
    var b = a.replace(/(\&gt;)/g, ">");
    var c = b.replace(/(\&amp;)/g, "\&");
    var d = c.replace(/(\&quot;)/g, "\"");
    return d;
  }
})